package com.kt.uokos.yimo.wx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Supplier;
import com.kt.uokos.yimo.anno.validator.Order;
import com.kt.uokos.yimo.anno.validator.Sort;
import com.kt.uokos.yimo.dao.*;

import com.kt.uokos.yimo.dao.System;
import com.kt.uokos.yimo.service.*;
import com.kt.uokos.yimo.util.ResponseUtil;
import com.kt.uokos.yimo.wx.annocation.LoginUser;
import com.kt.uokos.yimo.wx.config.SystemConfig;
import com.kt.uokos.yimo.wx.dao.User;
import com.kt.uokos.yimo.wx.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @Description TODO
 * @ClassName WxProductController
 * @Date 2022/1/5 1:38 PM
 * @Author KangTao
 */

@RestController
@RequestMapping("/wx")
@Validated
public class WxProductController {
    @Resource
    private ProductService productService;

    @Resource
    private GoodsAttributeService goodsAttributeService;

    @Resource
    private GoodsProductService goodsProductService;

    @Resource
    private GoodsSpecificationService goodsSpecificationService;

    @Resource
    private IssueService issueService;

    @Resource
    private BrandService brandService;

    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;
    
    @Resource
    private GroupRulesService groupRulesService;

    @Resource
    private CollectService collectService;

    @Resource
    private FootprintService footprintService;

    @Resource
    private SearchHistoryService searchHistoryService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private SystemConfigService systemConfigService;



    private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

    private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(16, 16, 1000, TimeUnit.MILLISECONDS, WORK_QUEUE, HANDLER);

    @GetMapping("/goods/detail")
    public Object detail(@LoginUser Integer userId,@NotNull Integer id){

        //商品基本信息
        Product info = productService.queryByProId(id);
        //商品参数
        Callable<List> goodsAttributeListCallable = () ->goodsAttributeService.queryGoodsAttribute(id);
        //商品规格
        Callable<Object> goodsSpecificationCallable = () -> goodsSpecificationService.getSpecificationVoList(id);
        //商品货品图片 数量 价格等
        Callable<List> goodsProductCallable = () -> goodsProductService.queryGoodsProperty(id);
        //基本问题
        Callable<List> questionListCallable = () -> issueService.querySelective("",0,6,"add_time","desc");
        //商品品牌
        Callable<Brand> brandCallable = () -> {
            Integer brandId = info.getBrandId();
            Brand brand;
            if (brandId == null) {
                brand = new Brand();
            } else {
                brand = brandService.findById(brandId);
            }
            return brand;
        };
        //用户评论
        Callable<Map> commentCallable = () -> {
            HashMap<String, Object> commentList = new HashMap<>();
            List<Comment> comments = commentService.queryByPid(id, 0, 2, "add_time", "desc");
            ArrayList<Map<String,Object>> commentdata = new ArrayList<>();
            for (Comment comment : comments){
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("id",comment.getId());
                hashMap.put("addTime",comment.getAddTime());
                hashMap.put("content", comment.getContent());
                hashMap.put("adminContent", comment.getAdminContent());
                User user = userService.queryById(comment.getUserId());
                hashMap.put("nickname", user == null ? "" : user.getNickname());
                hashMap.put("avatar", user == null ? "" : user.getAvatar());
                hashMap.put("picList", comment.getPicUrls());
                commentdata.add(hashMap);
            }
            commentList.put("count", PageInfo.of(comments).getTotal());
            commentList.put("data",commentdata);
            return commentList;
        };
        //团购
        Callable<List>  groupRulesCallable= () -> groupRulesService.queryByPid(id);
        //用户收藏
        int userHasCollect = 0;
        if (userId != null) {
            userHasCollect = collectService.countById(userId,(byte) 0,id);
        }

        //用户足迹

        if (userId != null) {
            executorService.execute(()->{
                Footprint footprint = new Footprint();
                footprint.setUserId(userId);
                footprint.setGoodsId(id);
                footprintService.add(footprint);
            });
        }

        FutureTask<List> goodsAttributeFutureTask = new FutureTask<>(goodsAttributeListCallable);
        FutureTask<Object> goodsSpecificationFutureTask = new FutureTask<>(goodsSpecificationCallable);
        FutureTask<List> goodsProductFutureTask = new FutureTask<>(goodsProductCallable);
        FutureTask<List> questionListFutureTask = new FutureTask<>(questionListCallable);
        FutureTask<Brand> brandFutureTask = new FutureTask<>(brandCallable);
        FutureTask<Map> commentFutureTask = new FutureTask<>(commentCallable);
        FutureTask<List> groupRulesFutureTask = new FutureTask<>(groupRulesCallable);



        executorService.submit(goodsAttributeFutureTask);
        executorService.submit(goodsSpecificationFutureTask);
        executorService.submit(goodsProductFutureTask);
        executorService.submit(questionListFutureTask);
        executorService.submit(brandFutureTask);
        executorService.submit(commentFutureTask);
        executorService.submit(groupRulesFutureTask);

        HashMap<String, Object> map = new HashMap<>();
        try {
            map.put("info",info);
            map.put("attribute",goodsAttributeFutureTask.get());
            map.put("specificationList",goodsSpecificationFutureTask.get());
            map.put("productList",goodsProductFutureTask.get());
            map.put("issue",questionListFutureTask.get());
            map.put("brand",brandFutureTask.get());
            map.put("comment",commentFutureTask.get());
            map.put("groupon",groupRulesFutureTask.get());
            map.put("userHasCollect",userHasCollect);
            String KeyName = SystemConfig.YIMO_WX_SHARE;
            List<System> systems = systemConfigService.quaryWxShare(KeyName);
            Boolean keyValue = Boolean.valueOf(systems.get(0).getKeyValue());
            map.put("share", keyValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("shareImage",info.getShareUrl());
        return ResponseUtil.ok(map);
    }


    @GetMapping("/goods/related")
    public Object related(@NotNull Integer id){
        Product product = productService.queryByProId(id);
        if (product ==null){
            return ResponseUtil.errs();
        }
        List<Product> productList = productService.queryByCatId(product.getCategoryId(), 0, 6, "add_time", "desc");
        //查找其同一类目下的商品
        return ResponseUtil.okList(productList);
    }


    @GetMapping("/goods/list")
    public Object search(Integer categoryId,
                         Integer brandId,
                         String keyword,
                         Boolean isNew,
                         Boolean isHot,
                         @LoginUser Integer userId,
                         @RequestParam(defaultValue = "1")Integer page,
                         @RequestParam(defaultValue = "10")Integer size,
                         @Sort(accepts = {"add_time","retail_price","name"})@RequestParam(defaultValue = "add_time")String sort,
                         @Order@RequestParam(defaultValue = "desc")String order){
                //将用户搜索记录添加到搜索历史
                if (userId != null&& !StringUtils.isEmpty(keyword)){
                    SearchHistory searchHistory = new SearchHistory();
                    searchHistory.setUserId(userId);
                    searchHistory.setKeyword(keyword);
                    searchHistory.setFrom("wx");
                    searchHistoryService.add(searchHistory);
                }

        //查询所有符合标准商品
        List<Product> productList = productService.querySelective(categoryId, brandId, keyword, isNew, isHot, page, size, sort, order);
        //查询其商品所属类目
        List<Integer> CatIds = productService.queryCatId(brandId, keyword, isHot, isNew);
        List<Category> categoryList;
        if (CatIds.size() != 0) {
            categoryList = categoryService.queryL2ById(CatIds);
        } else {
            categoryList = new ArrayList<>(0);
        }


        PageInfo<Product> pagedList = PageInfo.of(productList);

        Map<String, Object> map = new HashMap<>();
        map.put("list", productList);
        map.put("total", pagedList.getTotal());
        map.put("page", pagedList.getPageNum());
        map.put("limit", pagedList.getPageSize());
        map.put("pages", pagedList.getPages());
        map.put("filterCategoryList", categoryList);
        return ResponseUtil.ok(map);
    }


    //在其小程序界面显示父类目 本类目与同级类目
    @GetMapping("/goods/category")
    public Object category(@NotNull Integer id) {
        //获取本类目
        Category cur = categoryService.queryById(id);
        //父类目
        Category parent = categoryService.queryById(cur.getPid());
        //同级类目
        List<Category> children = categoryService.queryByPid(cur.getPid());
        Map<String, Object> data = new HashMap<>();
        data.put("currentCategory", cur);
        data.put("parentCategory", parent);
        data.put("brotherCategory", children);
        return ResponseUtil.ok(data);
    }



    @GetMapping("/goods/count")
    public Object info() {
        int data = productService.count();
        return ResponseUtil.ok(data);
    }
}
